﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using MouseExtender.Logic.Entities;

namespace MouseExtender.Logic.Managers
{
    public class InternetAccessManager
    {
        static InternetAccessManager()
        {
            //ignore all certificate error when accesing https resources
            ServicePointManager.ServerCertificateValidationCallback = (obj, sert, chain, error) => { return true; };
        }

        /// <summary>
        /// Call this method every time internet access settings changed
        /// </summary>
        public static void Initialize()
        {
            UserSettings settings = SettingsManager.CurrentSettings;
            IWebProxy defaultProxy = null;

            switch (settings.InternetAccessConfigType.Value)
            {
                case Enums.InternetAccessConfigurationType.AutoDetect:
                    defaultProxy = WebRequest.GetSystemWebProxy();
                    defaultProxy.Credentials = CredentialCache.DefaultNetworkCredentials;
                    break;
                case Enums.InternetAccessConfigurationType.Manual:
                    var proxy = new WebProxy(settings.HttpProxy);
                    if (!settings.UseProxyAuthentication)
                        proxy.UseDefaultCredentials = true;
                    else
                        proxy.Credentials = new NetworkCredential(settings.ProxyUserName, settings.ProxyPassword);

                    defaultProxy = proxy;
                    break;
                default:
                    throw new NotImplementedException();
            }

            //reinit global default webproxy. no need to manuaally assign proxy to each request
            WebRequest.DefaultWebProxy = defaultProxy;
        }
    }
}
